import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  //购物车列表
  const cartList =ref([])
   //订单列表
  const myOrderList = ref([])
  const addItem =(playload)=>{
      const index = cartList.value.findIndex(item=>item.id==playload.id)
      if(index>-1)
      {
        cartList.value[index].count++
      }else
      {
         cartList.value.push({
            ...playload,
            count:1,
            checked:false
         })
      }
  }
   
//删除
const delItem =(id)=>{
    cartList.value=cartList.value.filter(item=>item.id !=id)
}

  //总数量
const totalCount =computed(()=>{
    let res =0
    cartList.value.forEach(item=>{
        res += item.count
    })
    return res
})

//总价格
const totalPrice=computed(()=>{
    let res = 0
    cartList.value.forEach(item=>{
        if(item.checked==true)
        {
            res +=item.count*item.price
        }
    })
    return res.toFixed(2)
})

//修改数量++
 const updateAddCount =( id)=>{
    return cartList.value.find(item=>item.id==id).count++
 }

 //修改数量--
 const updateSubCount =( id)=>{
    return cartList.value.find(item=>item.id==id).count--
 }
 
 const orderList=computed(()=>{
    return cartList.value.filter(item=>item.checked==true)
 })


 const addOrderList =(payload)=>{
    myOrderList.value.push(payload)
 }

  return {cartList,addItem,totalCount,totalPrice,updateAddCount,updateSubCount,myOrderList,orderList,addOrderList,delItem }
},{
    persist:true
})